﻿using APP.BaseClass;
using APP.Image;
using APP.IO;
using APP.Log;
using APP.Windows;
using Newtonsoft.Json;
using NotifyPropertyBase;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ScreenCapture.Model
{
    public enum WindowType
    {
        Picture,  //图片仅可在主画布上展示
        RealWindow//真实窗口可进行 实时录制动作
    }

    /// <summary>
    /// 一个窗口的基本信息
    /// </summary>
    public class WindowInfo : ObservableObject
    {
        public string ProcessName { get; set; }
        public string WindowName { get; set; }
        public string WindowTitleMatchRule { get; set; }
        //public string WindowRect { get; set; }
        public string RecordScreenResolution { get; set; }

        /// <summary>
        /// 临时用非固定不变
        /// </summary>
        public IntPtr WinTempIntPtr { get; set; }

        public System.Drawing.Rectangle WindowRect { get; set; }

        [JsonIgnore]
        public System.Drawing.Bitmap FullScreenImageBitmap { get; set; }
        //public System.Drawing.Bitmap WinImageBitmap { get; set; }
        public string WinPicSavePath { get; set; }
        public WindowType WindowType { get; set; }

        public System.Drawing.Rectangle WindowsInnerRect { get; set; }
        public System.Drawing.Rectangle WindowsInnerRectForFullScreen { get; set; }

        private bool _IsSelect;
        /// <summary>
        /// 是否选中
        /// </summary>
        public bool IsSelect { get => _IsSelect; set => Set(ref _IsSelect, value); }

        /// <summary>
        ///  根据名称 重新获取位置
        /// </summary>
        /// <returns></returns>
        public FeedBack<bool> ReCaptureAndSaveWindowImage()
        {
            FeedBack<bool> feedBack = new FeedBack<bool>();
            var captureResult = this.ReCaptureWindow();
            if (!captureResult.Success)
            {
                feedBack.Message = captureResult.Message;
                return feedBack;
            }
            this.WinPicSavePath = this.SaveWindowImage();
            feedBack.Success = true;

            return captureResult;
        }
        /// <summary>
        ///  根据名称 重新获取位置 包含内部
        /// </summary>
        /// <returns></returns>
        public FeedBack<string> ReCaptureAndSaveWindowInnerRectImage()
        {
            FeedBack<string> feedBack = new FeedBack<string>();
            var captureResult = this.ReCaptureWindow();
            if (!captureResult.Success)
            {
                feedBack.Message = captureResult.Message;
                return feedBack;
            }
            this.WinPicSavePath = this.SaveInnerWindowImage();
            feedBack.Success = true;
            feedBack.Data = this.WinPicSavePath;
            return feedBack;
        }

        /// <summary>
        /// 重新定位内部画板位置
        /// </summary>
        /// <exception cref="Exception"></exception>
        public void ReLocateWindowInnerRect()
        {
            //WindowsInnerRect
            if (WindowsInnerRect == System.Drawing.Rectangle.Empty)
            {
                throw new Exception($"请设置窗体内区域");
            }

            this.WindowsInnerRectForFullScreen = new System.Drawing.Rectangle(
                 this.WindowRect.X + this.WindowsInnerRect.X,
                 this.WindowRect.Y + this.WindowsInnerRect.Y,
             this.WindowsInnerRect.Width,
             this.WindowsInnerRect.Height);
        }

        /// <summary>
        /// 重新获取窗体位置 和截图
        /// </summary>
        /// <exception cref="Exception"></exception>
        public FeedBack<bool> ReCaptureWindow()
        {
            FeedBack<bool> result = new FeedBack<bool>();
            if (string.IsNullOrEmpty(ProcessName))
            {
                Log.Error($"进程名为空 需要先指定窗体区域 ");
                result.Message = $"需要先指定窗体区域";
                //throw new Exception($"需要先指定窗体区域");
            }
            //检测一下是否变位置了 或者已经关了
            //ComboBox一般都在窗体内 所以获取窗体区域是必须的
            //获取窗口矩形 和窗体句柄
            System.Drawing.Rectangle winRect = System.Drawing.Rectangle.Empty;
            if (this.WinTempIntPtr != IntPtr.Zero)
            {
                winRect = WindowHelper.GetWindowRectangle(this.WinTempIntPtr);
            }
            if (winRect == System.Drawing.Rectangle.Empty)
            {
                IntPtr winHwnd = IntPtr.Zero;
                winRect = WindowHelper.FindWindowRect(this.ProcessName, this.WindowName, StringCompareType.StartsWith, ref winHwnd);
                this.WinTempIntPtr = winHwnd;
                if (winRect == System.Drawing.Rectangle.Empty)
                {
                    Log.Error($"ZoneOCR Failed to find window by ProcessName:{this.ProcessName}, windowName:{this.WindowName}, matchRule:{this.WindowTitleMatchRule ?? ""}");
                    result.Message = $"没有找到窗体区域 【{this.ProcessName}】【{this.WindowName}】";
                    return result;
                    //throw new Exception($"ZoneOCR Failed to find window by ProcessName:{this.ProcessName}, windowName:{this.WindowName}, matchRule:{this.WindowTitleMatchRule ?? ""}");
                }
            }
            result.Success = true;
            this.WindowRect = winRect;
            //this.FullScreenImageBitmap = WindowHelper.GetFullScreen();
            this.FullScreenImageBitmap = ScreenHelper.CapturePrimaryScreen();

            return result;
        }

        /// <summary>
        /// 对指定的窗口进行截图保存
        /// </summary>
        /// <param name="windoInfo"></param>
        /// <returns></returns>
        public string SaveWindowImage()
        {
            //保存当前直定的窗口区域图片
            var winRectangle = this.WindowRect;
            var cutImg = ImageHelper.DrawImage(this.FullScreenImageBitmap, winRectangle.X, winRectangle.Y, winRectangle.Width, winRectangle.Height);
            string saveFolder = PathHelper.GetPath(FolderType.Temp, "Image");
            string combineFolder = System.IO.Path.Combine(saveFolder, System.DateTime.Now.ToString("yyyyMMddHHmm"));
            if (!System.IO.Directory.Exists(combineFolder))
            {
                System.IO.Directory.CreateDirectory(combineFolder);
            }
            string savePath = System.IO.Path.Combine(combineFolder, System.DateTime.Now.ToString("yyyyMMddHHmmssffff") + ".png");
            cutImg.Save(savePath, System.Drawing.Imaging.ImageFormat.Png);
            string windowImage = savePath;
            //保存当前直定的窗口区域图片
            return windowImage;
        }
        /// <summary>
        /// 对指定的窗口进行截图保存
        /// </summary>
        /// <param name="windoInfo"></param>
        /// <returns></returns>
        public string SaveInnerWindowImage()
        {
            //保存当前直定的窗口区域图片
            var winRectangle = this.WindowRect;
            if (WindowsInnerRect == System.Drawing.Rectangle.Empty)
            {
                throw new Exception($"请设置窗体内区域");
            }
            var innerRectangle = new System.Drawing.Rectangle(winRectangle.X + WindowsInnerRect.X, winRectangle.Y + WindowsInnerRect.Y, WindowsInnerRect.Width, WindowsInnerRect.Height);
            if (this.FullScreenImageBitmap == null)
            {
                throw new Exception($"全拼截图丢失");
            }
            var cutImg = ImageHelper.DrawImage(this.FullScreenImageBitmap, innerRectangle.X, innerRectangle.Y, innerRectangle.Width, innerRectangle.Height);
            string saveFolder = PathHelper.GetPath(FolderType.Temp, "Image");
            string combineFolder = System.IO.Path.Combine(saveFolder, System.DateTime.Now.ToString("yyyyMMddHHmm"));
            if (!System.IO.Directory.Exists(combineFolder))
            {
                System.IO.Directory.CreateDirectory(combineFolder);
            }
            string savePath = System.IO.Path.Combine(combineFolder, System.DateTime.Now.ToString("yyyyMMddHHmmssffff") + ".png");
            cutImg.Save(savePath, System.Drawing.Imaging.ImageFormat.Png);
            string windowImage = savePath;
            //保存当前直定的窗口区域图片
            return windowImage;
        }
    }
}
